package org.jeecg.modules.jiaozhen.controller;

import cn.hutool.http.HtmlUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.content.entity.ContentInfo;
import org.jeecg.modules.content.service.IContentInfoService;

import org.jeecg.modules.jiaozhen.ContentData;
import org.jeecg.modules.jiaozhen.RequestData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.security.rsa.RSASignature;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Description: 第三方平台信息
 * @Author: jeecg-boot
 * @Date: 2020-05-02
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "第三方平台信息")
@RestController
@RequestMapping("/jiaozhen/jiaozhen")
public class JiaozhenController {

//    private String url = "https://ai.xhtxs.net";
    private String url = "https://ai.xinhua-news.cn";
//    private String url = "https://ai.xinhua-news.cn";

//

    @Autowired
    protected RestTemplate restTemplate;



    @Autowired
    private IContentInfoService conContentInfoService;

    @AutoLog(value = "第三方平台信息-分页列表查询")
    @ApiOperation(value = "第三方平台信息-分页列表查询", notes = "第三方平台信息-分页列表查询")
    @PostMapping(value = "/jiaozhen")
    public Result<?> jiaozhen(HttpServletRequest req,@RequestBody Map<String,Object> reqMap) {
        QueryWrapper<ContentInfo> contentInfoQueryWrapper = new QueryWrapper<>();
        contentInfoQueryWrapper.eq("task_id",reqMap.get("taskNo")).last(" limit 1");
        ContentInfo contentInfo = conContentInfoService.getOne(contentInfoQueryWrapper);
        List<Map<String,Object>> result = checkContent(contentInfo.getContent());
        return Result.OK(result);
    }

    @AutoLog(value = "第三方平台信息-分页列表查询")
    @ApiOperation(value = "第三方平台信息-分页列表查询", notes = "第三方平台信息-分页列表查询")
    @PostMapping(value = "/jiaozhen2")
    public Result<?> jiaozhen2(HttpServletRequest req,@RequestBody Map<String,Object> reqMap) {
       String content = reqMap.get("content").toString();
       content = content.replaceAll("&nbsp;","");

        List<Map<String, Object>> result = new ArrayList<>();
        try {
           result = checkContent(content);
       }catch(Exception e){
            e.printStackTrace();
            return Result.error("较真接口调用失败，请联系管理员");
       }
        return Result.OK(result);
    }

    @Autowired
    private RedisUtil redisUtil;

    public String getToken () {
//        if(StringUtils.isEmpty(redisUtil.get("xinhua-token"))){
            String requestUrl = url + "/auth/session";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//            headers.set("Origin", "http://ai.xhtxs.net/");
            headers.set("Origin", "https://ai.xinhua-news.cn");
            MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();

            paramMap.add("username", "dndxxhjz");
            paramMap.add("password", "Dndxxh2024..");
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST,
                    httpEntity, String.class);
//            redisUtil.set("xinhua-token",responseEntity.getBody(),60*1000*60);
//        }
//
//        return redisUtil.get("xinhua-token").toString();
        return responseEntity.getBody();
    }

//    public static void main(String[] args) {
//        JiaozhenController jiaozhenController = new JiaozhenController();
//        List<Map<String,Object>> list = jiaozhenController.checkContent("全身关注");
//        System.out.println(list);
//    }

    public List<Map<String,Object>> checkContent (String content) {
        content = HtmlUtil.cleanHtmlTag(content);
        log.info("clear-------------------------------");
        log.info(content);

        String requestUrl = url + "/saas/aicheck/chinese_aicheck";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", "Bearer "+JSONObject.parseObject(JSONObject.parseObject(getToken()).getString("result")).getString("id_token"));

        RequestData requestData = new RequestData();

        List<ContentData> checkContentList = new ArrayList<>();
        ContentData contentData = new ContentData();
        contentData.setKey("content");
        contentData.setValue(content);
        checkContentList.add(contentData);
//
//        ContentData contentData1 = new ContentData();
//        contentData1.setKey("content");
//        contentData1.setValue("全神灌注");
//        checkContentList.add(contentData1);
        requestData.setCheckContentList(checkContentList);
        requestData.setLevel(0);
        requestData.setRet_method("sync");

        String requestJson = JSONObject.toJSONString(requestData);


        HttpEntity<String> httpEntity = new HttpEntity<>(requestJson, headers);

        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(20000);
        clientHttpRequestFactory.setReadTimeout(500);
        RestTemplate restTemplateDgDevice = new RestTemplate();

        restTemplateDgDevice.setRequestFactory(clientHttpRequestFactory);
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity,new ParameterizedTypeReference<String>() {});

//        ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, String.class);

        log.info("获取校验内容:{}", responseEntity.getBody());
        JSONObject retObject = JSONObject.parseObject(responseEntity.getBody());
        String retString = "";

        List<Map<String,Object>> retList = new ArrayList<>();
        if(null != retObject && retObject.get("data") !=null ){
            JSONArray dataList = (JSONArray)retObject.get("data");
            for(Object tempdata : dataList){
                    JSONArray tempDataJson = ((JSONObject) tempdata).getJSONArray("content");
                    for(Object tempdataContent : tempDataJson){
                        Map<String,Object> tempMap = new HashMap<>();

//                        String tempStr =
//                                ((JSONObject)tempdataContent).getString("errMsg")+":  错误词："
//                                + ((JSONObject)tempdataContent).getString("errWord")+":  建议词："+ ((JSONObject)tempdataContent).getString("corWord") + " <br>";
//                        retString += tempStr;
                        if( !((JSONObject)tempdataContent).getString("errLevel").equals("2")){

                            int pos = Integer.parseInt(((JSONObject)tempdataContent).getString("errPos"));
                            tempMap.put("errMsg",((JSONObject)tempdataContent).getString("errMsg"));
                            tempMap.put("errWord",((JSONObject)tempdataContent).getString("errWord"));
                            tempMap.put("corWord",((JSONObject)tempdataContent).getString("corWord"));
                            tempMap.put("errLevel",((JSONObject)tempdataContent).getString("errLevel"));
                            tempMap.put("index",content.substring(0,pos-1).split(((JSONObject)tempdataContent).getString("errWord")).length -1);
                            tempMap.put("pos",((JSONObject)tempdataContent).getString("errPos"));
                            retList.add(tempMap);
                        }

                    }

            }

        }
        return retList;
    }

    private static final String token = "wufanxin";



    @GetMapping(value = "/message")
    public String verifyToken(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        log.info("signature: {} nonce: {} echostr: {} timestamp: {}", signature, nonce, echostr, timestamp);
        if (this.checkSignature(signature, timestamp, nonce)) {
            log.info("token ok");
            return echostr;
        }
        return echostr;
    }

    private boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] str = new String[]{token, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp =  getSHA1(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    public static String getSHA1(String input) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            byte[] bytes = sha1.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
         } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
         }
    }


    @PostMapping(value = "/message")
    public String receiveMessage(HttpServletRequest request) throws Exception {

        WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        log.info(JSONObject.toJSONString(wxMpXmlMessage));
        System.out.println(JSONObject.toJSONString(wxMpXmlMessage));
        return "success";
    }

    private Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        inputStream = null;
        return map;
    }


}
